﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Fusion
{
    public class AnimationData
    {
		public string name = "";
        public List<int> indices; // frame cel indices
		public List<int> delays; // frame dealys
        public int loopback; // if loopback < 0 then looping = false
		public int loopcount;

        public int Length
		{ get { return indices.Count - 1; } }


        public AnimationData( int[] Indices, int[] Durations, int Loopback, int Loopcount )
		{
            indices = new List<int>( Indices );
            delays = new List<int>( Durations );

            loopback = Loopback;
            if( loopback > Length )
				loopback = Length;

			loopcount = Loopcount;
        }

		public AnimationData( int[] Indices, int CommonDuration, int Loopback, int Loopcount )
        {
			indices = new List<int>( Indices );

			delays = new List<int>();
			for( int i=0; i < indices.Count; i++ )
				delays.Add( CommonDuration );

            loopback = Loopback;
            if( loopback > Length )
                loopback = Length;

			loopcount = Loopcount;
		}

		public AnimationData( XElement element )
		{
			ReadFrom( element );
		}


		#region File

		public XElement Write()
		{
			return WriteTo( new XElement( "Animation" ) );
		}

		public XElement WriteTo( XElement to )
		{
			to.SetAttributeValue( "name", name );
			to.SetAttributeValue( "indices", name );
			to.SetAttributeValue( "delays", name );
			to.SetAttributeValue( "loopback", name );
			to.SetAttributeValue( "loopcount", name );
			return to;
		}

		public void ReadFrom( XElement element )
		{
            if( element == null )
                return;


			name = element.Attribute( "name" ).Value;
			indices = Secretary.ReadIntCSV( element.Attribute( "indices" ).Value );

			if( element.Attribute( "delays" ) != null )
				delays = Secretary.ReadIntCSV( element.Attribute( "delays" ).Value );
			else if( element.Attribute( "delay" ) != null )
			{
				int delay = Secretary.ReadInt( element.Attribute( "delay" ).Value );
				delays = new List<int>();
				for( int i=0; i < indices.Count; i++ )
					delays.Add( delay );
			}
			loopback = Secretary.ReadInt( element.Attribute( "loopback" ).Value );
			loopcount = Secretary.ReadInt( element.Attribute( "loopcount" ).Value );
		}

		#endregion
	}
}
